package com.feiyi.app.activity;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.feiyi.app.R;
import com.feiyi.app.adapter.RegionAdapter;
import com.feiyi.app.app.AppConstant;
import com.feiyi.app.base.BaseActivity;
import com.feiyi.app.bean.AddressDetailBean;
import com.feiyi.app.bean.CommonBean;

import com.feiyi.app.bean.RegionBean;
import com.feiyi.app.event.AddressEvent;
import com.feiyi.app.net.HttpMethods;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * @author wangliantao
 * @time 2018 11 2018/11/18 10:03 PM
 * @email 1346947404@qq.com
 * @package com.feiyi.app.activity
 * @describe： In me the tiger sniffs the rose
 */
public class CreateNewAddressActivity extends BaseActivity {

    Unbinder unbinder;
    @BindView(R.id.tv_district)
    TextView tv_district;
    @BindView(R.id.et_receive_name)
    EditText et_receive_name;
    @BindView(R.id.et_receive_telephone)
    EditText et_receive_telephone;
    @BindView(R.id.et_detail_address)
    EditText et_detail_address;
    @BindView(R.id.et_zipcode)
    EditText et_zipcode;
    @BindView(R.id.iv_select)
    ImageView iv_select;
    @BindView(R.id.tv_title_titlebar)
    TextView tvTitleBar;

    private String uid;
    private String sid;
    private String temp;
    private String districtId;
    private String provinceId;
    private String cityId;

    private String telephone;
    private String detailAddress;
    private String zipCode;
    private String receiveName;




    private PopupWindow choosePopupwindow;

    private List<RegionBean.DataBean.RegionsBean> mList1 = new ArrayList<>();
    private List<RegionBean.DataBean.RegionsBean> mList2 = new ArrayList<>();
    private List<RegionBean.DataBean.RegionsBean> mList3 = new ArrayList<>();
    private RegionAdapter mAdpter1;
    private RegionAdapter mAdpter2;
    private RegionAdapter mAdpter3;
    private static final String TAG = "main";
    private String defaultString = "0";

    private String title;
    private String address_id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_address);
        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        unbinder = ButterKnife.bind(this);
        uid = spUtils.getString(AppConstant.UID);
        sid = spUtils.getString(AppConstant.SID);
        Log.e(TAG, "onCreate: "+getIntent().getStringExtra("id") );
        if (null == getIntent().getStringExtra("id") || "null".equals(getIntent().getStringExtra("id"))){
            title = "新增地址";
            tvTitleBar.setText(title);
        }else {
            title = "修改地址";
            tvTitleBar.setText(title);
            address_id = getIntent().getStringExtra("id");
            getAddressDetail(address_id);
        }
    }
    private void getAddressDetail(String id){
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("uid",uid);
        builder.add("sid",sid);
        builder.add("address_id",id);
        RequestBody body = builder.build();
        HttpMethods.getInstance().info.getAddressDetail(AppConstant.ADDRESS_DETAIL_URL,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AddressDetailBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(AddressDetailBean addressDetailBean) {
                        setDatas(addressDetailBean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "获取用户地址详情失败  "+e.toString() );
                        dispose();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    private void setDatas(AddressDetailBean bean){
        tv_district.setText(bean.getData().getProvince_name()+bean.getData().getCity_name()+bean.getData().getDistrict_name());
        et_receive_name.setText(bean.getData().getConsignee());
        et_receive_telephone.setText(bean.getData().getMobile());
        et_detail_address.setText(bean.getData().getAddress());
        et_zipcode.setText(bean.getData().getZipcode());
        defaultString = bean.getData().getDefault_address();
        if (defaultString.equals("1")){
            iv_select.setImageResource(R.mipmap.setted_default);
        }else {
            iv_select.setImageResource(R.mipmap.set_default);
        }
        provinceId = bean.getData().getProvince();
        cityId = bean.getData().getCity();
        districtId = bean.getData().getDistrict();
    }

    private void getEditText(){
        receiveName = et_receive_name.getText().toString();
        telephone = et_receive_telephone.getText().toString();
        zipCode = et_zipcode.getText().toString();
        detailAddress = et_detail_address.getText().toString();
    }

    @OnClick({R.id.ll_district,R.id.iv_back_titlebar,R.id.but_add,R.id.iv_select})
    public void onClick(View view){

        switch (view.getId()){
            case R.id.ll_district:
                initPopWindow();
                break;
            case R.id.iv_back_titlebar:
                finish();
                break;
            case R.id.iv_select:
                if (defaultString.equals("1")){
                    defaultString = "0";
                    iv_select.setImageResource(R.mipmap.set_default);
                }else {
                    defaultString = "1";
                    iv_select.setImageResource(R.mipmap.setted_default);
                }
                break;
            case R.id.but_add:
                if (null != address_id){
                    refreshAddress();
                }else {
                    upDateAddress();
                }
                break;
        }

    }
    private void refreshAddress(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                getEditText();

                if (null == receiveName || receiveName.isEmpty()){
                    ToastUtils.showShort("收货人姓名不能为空");
                    return;
                }
                if (null == telephone || telephone.isEmpty()){
                    ToastUtils.showShort("收件人电话不能为空");
                    return;
                }
                if (null == detailAddress || detailAddress.isEmpty()){
                    ToastUtils.showShort("详细地址不能为空");
                    return;
                }
                if (null == zipCode || zipCode.isEmpty()){
                    ToastUtils.showShort("邮政编码不能为空");
                    return;
                }
                if (null == districtId || districtId.isEmpty() || null == provinceId || provinceId.isEmpty() || null == cityId || cityId.isEmpty()){
                    ToastUtils.showShort("省市县数据不能为空");
                    return;
                }
                FormBody.Builder builder = new FormBody.Builder();
                builder.add("name",receiveName);
                builder.add("mobile",telephone);
                builder.add("uid",uid);
                builder.add("sid",sid);
                builder.add("address_id",address_id);
                builder.add("district",districtId);
                builder.add("province",provinceId);
                builder.add("city",cityId);
                builder.add("address",detailAddress);
                builder.add("zipcode",zipCode);
                builder.add("default_address",defaultString);
                RequestBody body = builder.build();
                HttpMethods.getInstance().info.updateAddressDetail(AppConstant.UPDATE_ADDRESS_URL,body)
                        .observeOn(Schedulers.io())
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<CommonBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                addDisposable(d);
                            }

                            @Override
                            public void onNext(CommonBean commonBean) {
                                if (commonBean.getStatus().getSucceed() == 1){
                                    Log.e(TAG, "onNext: "+commonBean.getStatus().getSucceed() );
                                    ToastUtils.showShort("修改地址成功");
                                    EventBus.getDefault().post(new AddressEvent("refresh"));
                                    finish();
                                }else {
                                    ToastUtils.showShort("修改地址失败"+commonBean.getStatus().getError_desc());
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e(TAG, "修改地址失败"+e.toString() );
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        }).start();

    }

    private void upDateAddress(){

        getEditText();

        if (null == receiveName || receiveName.isEmpty()){
            ToastUtils.showShort("收货人姓名不能为空");
            return;
        }
        if (null == telephone || telephone.isEmpty()){
            ToastUtils.showShort("收件人电话不能为空");
            return;
        }
        if (null == detailAddress || detailAddress.isEmpty()){
            ToastUtils.showShort("详细地址不能为空");
            return;
        }
        if (null == zipCode || zipCode.isEmpty()){
            ToastUtils.showShort("邮政编码不能为空");
            return;
        }
        if (null == districtId || districtId.isEmpty() || null == provinceId || provinceId.isEmpty() || null == cityId || cityId.isEmpty()){
            ToastUtils.showShort("省市县数据不能为空");
            return;
        }
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("name",receiveName);
        builder.add("mobile",telephone);
        builder.add("uid",uid);
        builder.add("sid",sid);
        builder.add("district",districtId);
        builder.add("province",provinceId);
        builder.add("city",cityId);
        builder.add("address",detailAddress);
        builder.add("zipcode",zipCode);
        builder.add("default_address",defaultString);
        RequestBody body = builder.build();
        HttpMethods.getInstance().info.upDateAddress(AppConstant.ADD_ADDRESS_URL,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommonBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(CommonBean commonBean) {
//                        Log.e(TAG, "onNext: "+commonBean.getStatus() );
                        if (commonBean.getStatus().getSucceed() == 1) {
                            ToastUtils.showShort("上传地址成功");
                            EventBus.getDefault().post(new AddressEvent("update"));
                            finish();
                        }else {
                            ToastUtils.showShort("上传地址失败"+commonBean.getStatus().getError_desc());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString() );

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    private void initPopWindow(){
        View popupWindowView = getLayoutInflater().inflate(R.layout.popup_region, null);
        choosePopupwindow = new PopupWindow(popupWindowView,ViewGroup.LayoutParams.MATCH_PARENT , SizeUtils.dp2px(500), true);
        //菜单背景色
        ColorDrawable dw = new ColorDrawable(0xffffffff);
        choosePopupwindow.setBackgroundDrawable(dw);
        choosePopupwindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_new_address, null), Gravity.BOTTOM, 0, 0);
        final TextView tv_region_1 = popupWindowView.findViewById(R.id.tv_region_1);
        final TextView tv_region_2 = popupWindowView.findViewById(R.id.tv_region_2);
        final TextView tv_region_3 = popupWindowView.findViewById(R.id.tv_region_3);
        final View view_region_1 = popupWindowView.findViewById(R.id.view_region_1);
        final View view_region_2 = popupWindowView.findViewById(R.id.view_region_2);
        final View view_region_3 = popupWindowView.findViewById(R.id.view_region_3);
        final RecyclerView rv_region_1 = popupWindowView.findViewById(R.id.rv_region_1);
        final RecyclerView rv_region_2 = popupWindowView.findViewById(R.id.rv_region_2);
        final RecyclerView rv_region_3 = popupWindowView.findViewById(R.id.rv_region_3);
        ImageView btn_close = popupWindowView.findViewById(R.id.iv_close);
        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choosePopupwindow.dismiss();
            }
        });
        rv_region_1.setLayoutManager(new LinearLayoutManager(this));
        rv_region_2.setLayoutManager(new LinearLayoutManager(this));
        rv_region_3.setLayoutManager(new LinearLayoutManager(this));
        rv_region_1.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        rv_region_2.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        rv_region_3.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mAdpter1 = new RegionAdapter(R.layout.item_region,mList1);
        mAdpter2 = new RegionAdapter(R.layout.item_region,mList2);
        mAdpter3 = new RegionAdapter(R.layout.item_region,mList3);
        rv_region_1.setAdapter(mAdpter1);
        rv_region_2.setAdapter(mAdpter2);
        rv_region_3.setAdapter(mAdpter3);
        tv_region_2.setVisibility(View.GONE);
        view_region_2.setVisibility(View.GONE);
        tv_region_3.setVisibility(View.GONE);
        view_region_3.setVisibility(View.GONE);
        getRegion("1",1);
        rv_region_1.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                tv_region_1.setTextColor(getResources().getColor(R.color.black));
                view_region_1.setVisibility(View.GONE);
                tv_region_1.setText(mList1.get(position).getName());
                makeDatas(mList1,position);
                mAdpter1.notifyDataSetChanged();
                rv_region_3.setVisibility(View.GONE);
                rv_region_1.setVisibility(View.GONE);
                rv_region_2.setVisibility(View.VISIBLE);
                tv_region_2.setVisibility(View.VISIBLE);
                view_region_2.setVisibility(View.VISIBLE);
                getRegion(mList1.get(position).getId(),2);
                temp = mList1.get(position).getName();
                provinceId = mList1.get(position).getId();
            }
        });
        rv_region_2.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                tv_region_2.setTextColor(getResources().getColor(R.color.black));
                view_region_2.setVisibility(View.GONE);
                tv_region_2.setText(mList2.get(position).getName());
                makeDatas(mList2,position);
                mAdpter2.notifyDataSetChanged();
                rv_region_2.setVisibility(View.GONE);
                rv_region_3.setVisibility(View.VISIBLE);
                tv_region_3.setVisibility(View.VISIBLE);
                view_region_3.setVisibility(View.VISIBLE);
                getRegion(mList2.get(position).getId(),3);
                temp = temp+mList2.get(position).getName();
                cityId = mList2.get(position).getId();
            }
        });

        rv_region_3.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                tv_region_3.setTextColor(getResources().getColor(R.color.black));
                view_region_3.setVisibility(View.GONE);
                tv_region_3.setText(mList3.get(position).getName());
                makeDatas(mList3,position);
                mAdpter3.notifyDataSetChanged();
                temp = temp+mList3.get(position).getName();
                districtId = mList3.get(position).getId();
                choosePopupwindow.dismiss();

            }
        });
        tv_region_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rv_region_1.setVisibility(View.VISIBLE);
                rv_region_2.setVisibility(View.GONE);
                rv_region_3.setVisibility(View.GONE);
                view_region_1.setVisibility(View.VISIBLE);
                view_region_2.setVisibility(View.GONE);
                view_region_3.setVisibility(View.GONE);
            }
        });
        tv_region_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rv_region_1.setVisibility(View.GONE);
                rv_region_2.setVisibility(View.VISIBLE);
                rv_region_3.setVisibility(View.GONE);
                view_region_1.setVisibility(View.GONE);
                view_region_2.setVisibility(View.VISIBLE);
                view_region_3.setVisibility(View.GONE);
            }
        });
        tv_region_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rv_region_1.setVisibility(View.GONE);
                rv_region_2.setVisibility(View.GONE);
                rv_region_3.setVisibility(View.VISIBLE);
                view_region_1.setVisibility(View.GONE);
                view_region_2.setVisibility(View.GONE);
                view_region_3.setVisibility(View.VISIBLE);
            }
        });

        //设置背景半透明
        backgroundAlpha(0.5f);
        //关闭事件
        choosePopupwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
                tv_district.setText(temp);
                temp = "";
                mList1.clear();
                mList2.clear();
                mList3.clear();

            }
        });

        popupWindowView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /*if( popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    popupWindow=null;
                }*/
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                return false;
            }
        });
    }
    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
    private void getRegion(String parent_id, final int level){

        FormBody.Builder builder = new FormBody.Builder();
        builder.add("parent_id",parent_id);
        RequestBody body = builder.build();

        HttpMethods.getInstance().info.getRegion(AppConstant.REGION,body).
                subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RegionBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(RegionBean regionBean) {

//                        Log.e(TAG, "onNext: 111" );
                        if (level == 1){
                            mList1.addAll(regionBean.getData().getRegions());
                        } else if (level == 2) {
                            mList2.addAll(regionBean.getData().getRegions());
                        }else {
                            mList3.addAll(regionBean.getData().getRegions());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "获取省市县失败 "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                        if (level == 1){
                            mAdpter1.setNewData(makeDatas(mList1,-1));
                            mAdpter1.notifyDataSetChanged();
                        }else if (level == 2){
                            mAdpter2.setNewData(makeDatas(mList2,-1));
                            mAdpter2.notifyDataSetChanged();
                        }else {
                            mAdpter3.setNewData(makeDatas(mList3,-1));
                            mAdpter3.notifyDataSetChanged();
                        }

                    }
                });

    }

    private List<RegionBean.DataBean.RegionsBean> makeDatas(List<RegionBean.DataBean.RegionsBean> list,int position){
        for (int i = 0; i < list.size(); i++) {
            if (position == -1){
                list.get(i).setSelected(false);
            }else {
                if (position == i){
                    list.get(i).setSelected(true);
                    continue;
                }else {
                    list.get(i).setSelected(false);
                }
            }

        }
        return list;
    }

}
